<template>
    <div class="data-read">
        <template v-if="form.dataType===0">
            <div class="tips-box">
                <i class="el-icon-warning"></i>
                <span>本地文件仅支持csv、txt、tsv，文件大小≤1G</span>
            </div>
            <el-form-item label="文件上传" prop="fileList">
                <el-upload class="upload-box" action="/dataSource/file-upload/uploadDataFile" :on-exceed="handleExceed" :on-remove="handleRemove" :on-success="uploadSuccess" :before-upload="beforeUpload" accept="multipart/form-data" :limit="1" :headers="headers" :multiple="false" :data="{ projectId }" :file-list="form.fileList">
                    <el-button size="small" class="select-file-btn" type="primary">上传文件</el-button>
                </el-upload>
            </el-form-item>
        </template>
        <template v-if="form.dataType===1">
            <el-form-item label="HDFS路径" prop="filePath">
                <el-input clearable v-model="form.filePath" placeholder="请输入HDFS路径"></el-input>
                <i class="iconfont icon-wenjianjia" @click="files.show=true"></i>
            </el-form-item>
        </template>
        <template v-if="form.dataType===2">
            <el-form-item label="数据源" prop="sourceId">
                <el-select clearable filterable v-model="form.sourceId" placeholder="请选择数据源" @change="changeOrigin">
                    <el-option v-for="(item, i) in dataOrigins" :key="i" :label="item.sourceName" :value="item.sourceId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="数据库名" prop="databaseSchema">
                <el-select clearable filterable v-model="form.databaseSchema" placeholder="请选择数据库名" @change="changeSchemas">
                    <el-option v-for="(item, i) in schemas" :key="i" :label="item" :value="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="数据表" prop="srcTableName">
                <el-select clearable @change="changeDataOriginsTables" filterable v-model="form.srcTableName" placeholder="请选择数据表">
                    <el-option v-for="(item, i) in dataOriginsTables" :key="i" :label="item" :value="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="选择字段" prop="inputColumns">
                <select-field :item="isDisabled" :list="form.inputColumns" @save="handleSelectField"></select-field>
            </el-form-item>
            <el-form-item label="切分键">
                <el-select clearable filterable v-model="form.splitKey" placeholder="请选择切分键">
                    <el-option v-for="(item, i) in form.splitKeyList" :key="i" :label="item" :value="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="并行度" prop="parallelism">
                <el-input clearable v-model="form.parallelism" placeholder="请输入并行度"></el-input>
            </el-form-item>
            <el-form-item>
                <template slot="label">
                    <span>条件表达式</span>
                    <el-tooltip class="item" effect="dark" content="数据过滤，填写where过滤语句，只需填写where 后面的字句，  如 age>3" placement="top">
                        <span class="tips-box1"><i class="el-icon-warning"></i></span>
                    </el-tooltip>
                </template>
                <el-input clearable v-model="form.conditionExp" placeholder="请输入条件表达式"></el-input>
            </el-form-item>
            <el-form-item label="脏数据条数">
                <el-input clearable oninput="value=value.replace(/[^\d.]/g,'')" v-model="form.errorRecord" placeholder="请输入脏数据条数"></el-input>
            </el-form-item>
            <el-form-item label="脏数据百分比">
                <el-input clearable v-model="form.errorPercentage" placeholder="请输入脏数据百分比"></el-input>
            </el-form-item>
        </template>
        <template v-if="[0,1].includes(form.dataType)">
            <el-form-item label="文件类型" prop="fileType">
                <el-select v-model="form.fileType" placeholder="请选择文件类型" @change="changeFileType">
                    <el-option v-show="form.dataType===0?i<3:i<4" v-for="(item, i) in fileTypes" :key="i" :label="item.name" :value="item.name"></el-option>
                </el-select>
            </el-form-item>
            <template v-if="form.fileType!=='PARQUET'">
                <el-form-item label="列分隔符">
                    <template slot="label">
                        <span>列分隔符</span>
                        <el-tooltip class="item" effect="dark" content="填写相应符号的ASCII码的十六进制，典型符号如：逗号(0x2C)，制表符(0x09)，空格(0x20)" placement="top">
                            <span class="tips-box1"><i class="el-icon-warning"></i></span>
                        </el-tooltip>
                    </template>
                    <el-input clearable v-model="form.columnDelimiter" placeholder="请输入列分隔符"></el-input>
                </el-form-item>
                <el-form-item label="日期格式">
                    <el-input clearable v-model="form.dateFormat" placeholder="yyyy-MM-dd" @change="changeTime($event,'dateFormat','yyyy-MM-dd')"></el-input>
                </el-form-item>
                <el-form-item label="时间格式">
                    <el-input clearable v-model="form.timeFormat" placeholder="yyyy-MM-dd HH:mm:ss" @change="changeTime($event,'timeFormat','yyyy-MM-dd HH:mm:ss')"></el-input>
                </el-form-item>
                <el-form-item label="时间戳格式">
                    <el-input clearable v-model="form.timestampFormat" placeholder="yyyy-MM-dd HH:mm:ss.SSS" @change="changeTime($event,'timestampFormat','yyyy-MM-dd HH:mm:ss.SSS')"></el-input>
                </el-form-item>
                <el-form-item label="字符集编码" prop="characterEncoding">
                    <el-select v-model="form.characterEncoding" placeholder="请选择字符集编码">
                        <el-option label="UTF-8" value="UTF-8"></el-option>
                        <el-option label="GBK" value="GBK"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="last-form-item" label="文件首行为列名">
                    <el-switch v-model="form.existsHeader"></el-switch>
                </el-form-item>
            </template>
        </template>
        <select-file :files="files" @save="getHDFSpath"></select-file>
        <multiple-select-field v-if="multiple.show" :data="multiple" @save="handleSave" v-model="multipleVal"></multiple-select-field>
    </div>
</template>
<script>
import {
    mapGetters,
    mapMutations
} from 'vuex'
import SelectFile from './SelectFile'
import SelectField from '@/components/SelectField'
import MultipleSelectField from '@/components/MultipleSelectField'
export default {
    name: 'DataRead',
    props: {
        form: {
            type: Object
        }
    },
    computed: {
        ...mapGetters({
            projectId: 'common/getProjectId',
            dataTables: 'common/getDataTables',
            dataOrigins: 'common/getDataOrigins',
            schemas: 'common/getSchemas',
            dataOriginsTables: 'common/getDataOriginsTables',
            importSourceTableField: 'common/getImportSourceTableField'
        })
    },
    components: { SelectFile, SelectField, MultipleSelectField },
    data () {
        return {
            isDisabled: {
                disabled: false,
                isDisabled: false
            },
            multipleVal: '',
            multiple: {
                title: '选择字段',
                show: false,
                isNumber: false, // 多输入列选择框，多个列选择弹窗，只能选择数值类型的
                data: []
            },
            files: {
                title: '选择文件',
                placeholder: '请选择文件',
                show: false,
                filePath: null
            },
            headers: {
                Authentication: JSON.parse(localStorage.getItem('USER_TOKEN'))
            },
            fileTypes: [
                { name: 'CSV', col: '0x2C' },
                { name: 'TSV', col: '0x09' },
                { name: 'TXT', col: '0x20' },
                { name: 'PARQUET', col: '' }
            ],
            previewData: {}
        }
    },
    created () {
        // 初始化
        if (this.isSelectFiled()) {
            this.getPreviewData()
        }
    },
    methods: {
        ...mapMutations({
            setSchemas: 'common/setSchemas',
            setDataOriginsTables: 'common/setDataOriginsTables',
            setPreviewData: 'common/setPreviewData'
        }),
        // 切换数据表
        changeDataOriginsTables (val) {
            this.form.conditionExp = null
            if (!val) {
                this.form.inputColumns = []
                this.form.splitKeyList = []
                this.form.splitKey = null
                this.multipleVal = ''
            }
            if (this.isSelectFiled()) {
                this.getPreviewData(true)
            }
        },
        // 在选择字段之前判断是否已经选择了数据源，scheme，数据表，缺一不可，flag为true的时候给出提示
        isSelectFiled (flag) {
            const { sourceId, databaseSchema, srcTableName } = this.form
            if (!sourceId) {
                flag && this.$message.error('请选择数据源')
                return false
            }
            if (!databaseSchema) {
                flag && this.$message.error('请选择数据库名')
                return false
            }
            if (!srcTableName) {
                flag && this.$message.error('请选择数据表')
                return false
            }
            return true
        },
        // 点击选择字段按钮事件
        handleSelectField () {
            if (this.isSelectFiled(true)) {
                this.multiple.show = true
            }
        },
        // 选择字段弹窗保存事件
        handleSave (type, data) {
            this.form.inputColumns = data.split(',')
            this.multipleVal = data
            this.multiple.show = false
        },
        // 获取所有字段信息，flag为true的时候是全选字段，否则用回显字段
        getPreviewData (flag) {
            const { parallelism, conditionExp, databaseSchema, sourceId, srcTableName } = this.form
            const url = '/dataSource/file-upload/previewDataTable'
            const params = {
                projectId: this.projectId,
                sourceId,
                tableName: srcTableName,
                databaseSchema,
                parallelism,
                conditionExp,
                inputColumns: []
            }
            this.$post(url, params).then(res => {
                if (res) {
                    const { schema, fileSize, records } = res
                    if (flag) {
                        let arr = schema.map(v => v.name)
                        this.form.inputColumns = arr
                        this.form.splitKeyList = arr
                    }
                    this.multipleVal = this.form.inputColumns.join(',')
                    this.multiple.data = schema
                    this.previewData = {
                        cols: schema.length || 0,
                        fileSize,
                        records,
                        schema
                    }
                    this.setPreviewData(this.previewData)
                }
            })
        },
        getHDFSpath (val) {
            const item = val ? this.dataTables.filter(v => v.filePath === val)[0] : null
            this.autoSetInfo(item)
            this.files.show = false
        },
        // 切换schema
        changeSchemas (databaseSchema) {
            this.form.srcTableName = null
            this.form.inputColumns = []
            this.form.splitKeyList = []
            this.form.splitKey = null
            this.multipleVal = ''
            this.form.conditionExp = null
            this.setDataOriginsTables([])
            if (databaseSchema) {
                const params = {
                    projectId: this.projectId,
                    sourceId: this.form.sourceId,
                    databaseSchema
                }
                this.$post('/dataSource/queryDataSourceTables', params).then(res => {
                    res && this.setDataOriginsTables(res)
                })
            }
        },
        // 切换数据源
        changeOrigin (sourceId) {
            this.form.databaseType = null
            this.form.srcTableName = null
            this.form.databaseSchema = null
            this.form.inputColumns = []
            this.form.splitKeyList = []
            this.form.splitKey = null
            this.multipleVal = ''
            this.form.conditionExp = null
            this.setSchemas([])
            this.setDataOriginsTables([])
            this.form.sourceId = sourceId
            if (sourceId) {
                this.form.databaseType = this.dataOrigins.filter(v => v.sourceId === sourceId)[0].databaseType
                const params = {
                    projectId: this.projectId,
                    sourceId,
                    pageSize: -1
                }
                this.$post('/dataSource/queryDataSourceSchemas', params).then(res => {
                    res && this.setSchemas(res)
                })
            }
        },
        uploadSuccess (res) {
            if (res.success) {
                this.$message.success('文件上传成功')
                const { fileName, filePath } = res.data
                this.form.fileList = [{
                    name: fileName,
                    url: filePath
                }]
                this.autoSetInfo(res.data)
            } else {
                this.form.fileList = []
                this.$message.error(res.errorHint)
            }
        },
        changeFileType (val) {
            this.form.columnDelimiter = val ? this.fileTypes.filter(v => v.name === val)[0].col : null
        },
        autoSetInfo (item) {
            if (item) {
                const { fileName, filePath } = item
                this.form.filePath = filePath
                let str = fileName.split('.')[1].toUpperCase()
                if (str === 'DAT') {
                    str = 'PARQUET'
                }
                this.form.fileType = str
                this.form.columnDelimiter = this.fileTypes.filter(v => v.name === str)[0].col
            } else {
                this.form.fileType = null
                this.form.filePath = null
                this.form.columnDelimiter = null
            }
        },
        handleExceed () {
            this.$message.error('只能上传一个文件，请删除当前文件后重新上传')
        },
        beforeUpload (file) {
            const arr = ['csv', 'txt', 'tsv']
            const str = file.name.split('.')[1].toLowerCase()
            if (!arr.includes(str)) {
                this.$message.error('目前只支持csv、tsv、txt格式的文本文件')
                return false
            }
            if (file.size > 1024 * 1024 * 1024) {
                this.$message.error('文件大小不能超过1024M')
                return false
            }
        },
        handleRemove () {
            this.form.fileList = []
        },
        changeTime (val, filed, value) {
            if (val === '') {
                this.form[filed] = value
            }
        }
    }
}
</script>
<style lang="less">
    .data-read {
        .last-form-item {
            .el-form-item__content {
                margin-left: 0 !important;
            }
        }
        .params-controls {
            width: 260px !important;
        }
        .tips-box {
            border: 1px solid #FFCC4B;
            padding: 5px 16px;
            color: rgba(51, 51, 51, .65);
            .el-icon-warning {
                color: #F3B230;
                font-size: 18px;
                margin-left: 12px;
            }
        }
        .upload-box {
            display: flex;
            height: 32px;
        }
        .icon-wenjianjia {
            font-size: 20px;
            margin-left: 5px;
            cursor: pointer;
        }
    }
</style>
